﻿using System;
using System.Collections.Generic;
using Microsoft.Security.Application;

namespace SacNetUG.Models
{
    public static class ModelHelpers
    {
        public static bool Exists<T>(this IEnumerable<T> collection, Func<T, bool> comparer)
        {
            foreach (var item in collection)
            {
                if (comparer(item))
                    return true;
            }
            return false;
        }

        //for controllers that use ValidateInput(false)
        //we need to strip out malicious content in the html
        public static void SanitizeInput<T>(this T webInput)
        {
            var properties = webInput.GetType().GetProperties();

            foreach (var info in properties)
            {
                if(info.PropertyType.FullName == "System.String")
                {

                    var s = info.GetValue(webInput, null);
                    if (s == null) continue;

                    //trim the return value to elimate \r\n it wraps value in
                    if (info.CanWrite)
                    {
                        info.SetValue(webInput, AntiXss.GetSafeHtmlFragment(s.ToString()).Trim(), null);
                    }
                    
                }
            }
        }
    }
}
